<template>
  <div v-if="orderDetails.id" class="content">
    <!-- Navbar -->
    <navBar title="医生问诊室"></navBar>
    <div v-if="orderDetails.status === 2" class="notice">
      已通知医生尽快接诊，24小时内医生未回复将自动退款
    </div>
    <div v-else class="notice consulting">
      <div>咨询中</div>
      <div class="time">剩余时间: {{ residueTime() }}</div>
    </div>
    <!-- 聊天框 -->
    <div class="chat">
      <div class="hint">{{ orderDetails.createTime }}</div>
      <van-cell-group inset>
        <van-cell>
          <template #title>
            <div class="title">
              {{ orderDetails.patientInfo.name }}
              {{ orderDetails.patientInfo.genderValue }}
              {{ `${orderDetails.patientInfo.age}岁` }}
            </div>
          </template>
          <template #label>
            <div class="label">
              {{ illnessTimes[orderDetails.illnessTime] }} |
              {{ orderDetails.consultFlag ? "就诊过" : "没就诊过" }}
            </div>
          </template>
        </van-cell>
        <van-cell class="desc">
          <template #title>
            <div class="left">病情描述</div>
            <div class="left">图片</div>
          </template>
          <template #value>
            <div class="value">{{ orderDetails.illnessDesc }}</div>
            <div class="value" @click="clickView">点击查看</div>
          </template>
        </van-cell>
      </van-cell-group>
      <div class="hint">医护人员正在赶来,请耐心等候</div>
      <div class="hint">
        <span class="text">温馨提示：</span
        >在线咨询不能代替面诊,医护人员建议仅供参考
      </div>
      <!-- 电子处方 -->
      <div class="prescription" v-if="orderDetails.prescriptionId">
        <div class="head">
          <div class="left">
            <div class="title">电子处方</div>
            <p class="value">马占山11 女 0岁 身体不适，请按照处方治疗</p>
            <p class="value">开方时间：2023-01-06 12:26:04</p>
          </div>
          <div class="right" @click="onPrescription">
            原始处方
            <van-icon name="arrow" />
          </div>
        </div>
        <div class="main">
          <div class="item">
            <div class="top">
              <div class="title">金乌骨通胶囊(神奇) 每粒装0.5g</div>
              <p class="desc">口服。一次3粒，一日3次。</p>
            </div>
            <span class="count">×10</span>
          </div>
          <div class="item">
            <div class="top">
              <div class="title">鸿茅药酒(鸿茅) 每瓶装:250毫升、500毫升</div>
              <p class="desc">口服，一次15毫升，一日2次。</p>
            </div>
            <span class="count">×6</span>
          </div>
          <div class="item">
            <div class="top">
              <div class="title">丁硼乳膏(雅皓) 每支装36克；每支装65克</div>
              <p class="desc">涂患处或涂在牙刷上刷牙,一次1g（乳膏长度1～1.5cm）,患坏死性牙龈炎及急性牙龈炎者可将乳膏涂抹患处或遵医嘱。一日３～４次,在口中滞留３～５分钟后清水漱口。</p>
            </div>
            <span class="count">×1</span>
          </div>
        </div>
        <van-button class="purchase" block color="#eaf8f6" @click="$router.push({path:'/order/pay',query:{id:orderDetails.prescriptionId}})">购买药品</van-button>
      </div>
      <ul class="list">
        <li class="item" :class="{doctor:item.name === 'doctor'}" v-for="(item,index) in valueList" :key="index">
          <img
          v-if="item.name === 'doctor'"
            class="photo"
            src="@/assets/upload/doctor-portrait@2x.png"
            alt=""
          />
          <div class="box">
            <div class="time">{{item.time}}</div>
            <div class="desc">{{item.msg}}</div>
          </div>
          <img
          v-if="item.name === 'my'"
            class="photo"
            src="@/assets/upload/my_photo.jpg"
            alt=""
          />
        </li>
      </ul>
    </div>
    <!-- 输入框 -->
    <div class="input_box">
      <input class="input" type="text" placeholder="问医生" />
      <van-uploader :after-read="afterRead">
        <img class="upload" src="@/assets/upload/upload-pic@2x.png" alt="" />
      </van-uploader>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { getOrderDetails, upload, referPrescription } from '@/api'
import { showImagePreview } from 'vant'
import { io } from 'socket.io-client'
import * as dayjs from 'dayjs'

const route = useRoute()
const store = useStore()

// 获取订单详情
const orderDetails = ref({})
const fetchOrderDetails = async () => {
  const { data } = await getOrderDetails(route.query.orderId)
  orderDetails.value = data
}
fetchOrderDetails()

// 咨询剩余时间
const times = ref(null)
const residueTime = () => {
  const createTime = +new Date(orderDetails.value.createTime)
  const currentTime = +new Date()
  times.value = 86400 - (currentTime - createTime) / 1000
  let h = Math.floor((times.value % (3600 * 24)) / (60 * 60)) // 获取时
  let m = Math.floor(((times.value % (3600 * 24)) % (60 * 60)) / 60) // 获取分
  let s = Math.floor(times.value % 60) // 获取秒
  h = h < 10 ? '0' + h : h
  m = m < 10 ? '0' + m : m
  s = s < 10 ? '0' + s : s
  return `${h}:${m}:${s}`
}
const timeId = setInterval(() => {
  if (times.value < 0) {
    clearInterval(timeId)
    return
  }
  residueTime()
}, 1000)

// 患病时间对应数据
const illnessTimes = {
  1: '一周内',
  2: '一月内',
  3: '半年内',
  4: '半年以上'
}

// 原始处方
const onPrescription = async () => {
  const { data } = await referPrescription(orderDetails.value.prescriptionId)
  showImagePreview([data.url])
}

// 聊天区域内容
const valueList = ref([
  { name: 'my', msg: '你好', time: dayjs(new Date()).format('HH:mm') },
  { name: 'doctor', msg: '你好', time: dayjs(new Date()).format('HH:mm') },
  { name: 'my', msg: '你有病吗', time: dayjs(new Date()).format('HH:mm') }
])

// 聊天-查询历史聊天记录
const getMsgHistory = () => {
  const socket = io('https://consult-api.itheima.net', {
    query: {
      token: store.state.login.userInfo.token
    },
    transports: ['websocket']
  })
  // 向socket服务端发送数据 参数：pageSize: number, lastTime: string, orderId: string
  socket.emit('getChatMsgList', 20, '2022-08-26', route.query.orderId)

  // 测试下是否建立链接成功
  socket.on('connect', () => {
    console.log('链接建立成功')
  })

  // 返回的聊天记录信息
  socket.on('chatMsgList', event => {
    console.log('event', event.msg)
  })
}
getMsgHistory()

// 点击查看
const pictures = ref([])
const clickView = () => {
  if (orderDetails.value.pictures.length !== 0) {
    orderDetails.value.pictures.forEach((item) =>
      pictures.value.push(item.url)
    )
    showImagePreview(pictures.value)
  }
}

// 上传图片
const afterRead = async (file) => {
  const { data } = await upload(file.file)
  console.log('data', data)
}
</script>

<style lang="scss" scoped>
.notice {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 90px;
  width: 100%;
  background-color: #eaf8f6;
  font-size: 26px;
  color: #16c2a3;
  line-height: 90px;
  text-align: center;
}
.consulting {
  display: flex;
  justify-content: space-between;
  padding: 0 30px;
  background-color: #fff;
  .time {
    color: #121826;
  }
}

// 聊天框
.chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 110px;
  padding: 210px 30px 0 30px;
  font-size: 25px;
  color: #c3c3c5;
  .hint {
    padding: 20px 30px;
    margin-bottom: 50px;
    border-radius: 66px;
    background-color: #fff;
    .text {
      color: #16c2a3;
    }
  }
  ::v-deep .van-cell-group {
    width: 100%;
    margin: 0 0 50px;
    .title {
      font-size: 32px;
      color: #121826;
    }
    .label {
      color: #c3c3c5;
    }
    .desc {
      .van-cell__title {
        flex: unset;
        width: 150px;
        .left {
          font-size: 25px;
          color: #121826;
        }
      }
      .van-cell__value {
        text-align: left;
        .value {
          font-size: 25px;
          color: #c3c3c5;
        }
      }
    }
  }

  // 电子处方
  .prescription{
    margin-bottom: 50px;
    border-radius: 16px 16px 0 0;
    width: 100%;
    background-color: #fff;
    font-size: 25px;
    line-height: 1.6;
    .head{
      display: flex;
      justify-content: space-between;
      padding: 30px;
      border-bottom: 1px solid #eee;
      .title{
        font-size: 32px;
        color: #121826;
      }
    }
    .main{
      padding: 30px 30px 0 30px;
      .item{
        display: flex;
        justify-content: space-between;
        margin-bottom: 30px;
        .top{
          .title{
            margin-bottom: 6px;
            color: #121826;
            font-size: 30px;
          }
          .desc{
            line-height: 1.3;
          }
        }
        .count{
          color: #121826;
        }
      }
    }
    ::v-deep .purchase{
      border-radius: unset;
      .van-button__text{
        font-size: 32px;
        color: #16c2a3;
      }
    }
  }

  .list {
    display: flex;
    flex-direction: column;
    width: 100%;
    .item {
      display: flex;
      align-self: flex-end;
      margin-bottom: 50px;
      .box{
        margin: 0 25px;
        .time {
          margin-bottom: 10px;
          text-align: right;
          font-size: 28px;
        }
        .desc {
          position: relative;
          padding: 30px;
          border-radius: 20px;
          background-color: #16c2a3;
          color: #fff;
          font-size: 28px;
          &::before{
            content: '';
            position: absolute;
            top: 20px;
            right: -26px;
            width: 26px;
            height: 26px;
            background-color: #16c2a3;
            border-top-right-radius: 30px 10px;
          }
          &::after{
            content: '';
            position: absolute;
            top: 26px;
            right: -27px;
            width: 27px;
            height: 22px;
            background-color: #f6f7f9;
            border-top-left-radius: 26px;
          }
        }
      }
      .photo {
        border-radius: 50%;
        width: 80px;
        height: 80px;
      }
    }
    .doctor{
      align-self: flex-start;
      .box{
        .time{
          text-align: left;
        }
        .desc{
          background-color: #fff;
          color: #121826;
          &::before{
            left: -26px;
            background-color: #fff;
            border-top-left-radius: 30px 10px;
            border-top-right-radius: unset;
          }
          &::after{
            left: -27px;
            border-top-right-radius: 26px;
            border-top-left-radius: unset;
          }
        }
      }
    }
  }
}

// 输入框
.input_box {
  display: flex;
  align-items: center;
  position: fixed;
  left: 0;
  bottom: 0;
  padding: 20px 30px;
  width: 100%;
  background-color: #fff;
  .input {
    flex: 1;
    border: 0;
    margin-right: 20px;
    padding-left: 30px;
    background-color: #f6f7f9;
    height: 80px;
    border-radius: 80px;
    font-size: 28px;
    color: #323233;
    &::-webkit-input-placeholder {
      color: #c3c3c5;
    }
  }
  .upload {
    width: 50px;
    height: 50px;
  }
}
</style>
